using Avalonia.BiliBili.Libs.Models;
using Avalonia.BiliBili.ViewModels;
using Bilibili.Common;
using Bilibili.Common.Log;
using Bilibili.WebClient.Api;
using DynamicData;
using PCLUntils.Objects;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Avalonia.BiliBili.Windows
{
    public partial class LiveCenterWindow : WindowBase
    {
        private LiveCenterClient Client { get; }
        private LiveCenterViewModel ViewModel { get; }
        public LiveCenterWindow()
        {
            InitializeComponent();
            Client = new LiveCenterClient();
            ViewModel = new LiveCenterViewModel();
        }
        protected override void AfterInitializeComponent()
        {
            this.DataContext = ViewModel;
            RunOnUiThread(async () =>
            {
                await UserInfo();
                await LoadMedals();
                await LoadTitles();
            });
        }
        private async Task UserInfo()
        {
            try
            {
                var model = await Client.GetUserInfo();
                if (model.IsSuccess())
                    ViewModel.UserInfo = model.Data;
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("UserInfo", ex);
            }
        }
        private async Task LoadTitles()
        {
            try
            {
                var result = await Client.GetUserTitle();
                if (result.IsSuccess())
                {
                    var m = result.Data;
                    if (m.IsNotEmpty() && m.code == 0)
                        ViewModel.Titles.AddRange(m.data.list);
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("LoadTitles", ex);
            }
        }
        private async Task LoadMedals()
        {
            try
            {
                var result = await Client.GetMedals();
                if (result.IsSuccess())
                {
                    var m = result.Data;
                    if (m.IsNotEmpty() && m.code == 0)
                    {
                        var medals = new List<LiveMedalModel>();
                        foreach (var item in m.data)
                            medals.Add(new LiveMedalModel(item));
                        ViewModel.Medals.AddRange(medals);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("LoadMedals", ex);
            }
        }
    }
}